import axios from 'axios'
import { store, loginOpen } from './store.js'
import { ElMessage } from 'element-plus'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const service = axios.create({
    baseURL: store.api,
    timeout: 9000
})

var loadTimer;

// 添加请求拦截器
service.interceptors.request.use(function (config) {
    // 是否验证token
    if (config.verify == true) {
        config.headers['Authorization'] = 'Bearer ' + loginOpen.getToken() // 每个请求携带自定义token
    }
    //loading
    if(!config.noload){
        loadTimer && clearTimeout(loadTimer);
        loadTimer = setTimeout(() => {
            store.loading = true;
        }, 500); 
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    clearTimeout(loadTimer);
    store.loading = false;
    console.log(error)
    return Promise.reject(error);
});

let isRefreshing = false; // 是否正在刷新token
// 添加响应拦截器
service.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    loadTimer && clearTimeout(loadTimer);
    store.loading = false;
    return response;
}, function (error) {
    // 对响应错误做点什么
    loadTimer && clearTimeout(loadTimer);
    store.loading = false;
    const res = error.response;
    if (!res) {
        ElMessage.error('无法连接服务器！');
        return Promise.reject(error);
    }
    if (res.status === 401) {
        try {
            if (isRefreshing) {
                throw { err: '正在获取签名，请等待...', refresh: true }
            }
            isRefreshing = true; // 设置正在刷新token
            var refresh = loginOpen.getRefreshToken();
            if (refresh) {// 刷新token
                return new Promise((resolve, reject) => {
                    service({
                        method: 'post',
                        url: '/login/refresh',
                        data: { refresh_token: loginOpen.getRefreshToken() },
                    }).then(res => {
                        isRefreshing = false;
                        var result = res.data;
                        if (result.state) {
                            loginOpen.setToken(result.token);
                            loginOpen.setRefreshToken(result.refresh_token);
                            loginOpen.loginnum++;
                            error.config.headers['Authorization'] = 'Bearer ' + result.token;
                            resolve(service(error.config));
                        } else {
                            result.msg = result.msg == 'TokenExpiredError' ? '签证过期，请重新登陆！' : result.msg;
                            loginOpen.clearToken();
                            resolve(res)
                        }
                    }).catch(err => {
                        err.response = { err: '刷新token失败！' }
                        err.status = 400;
                        reject(err)
                    })
                })
            } else {
                throw {}
            }
        } catch (error) {
            // 401 清除token并跳转登录页面
            if (!error.refresh) {
                loginOpen.clearToken();
                loginOpen.popup = true;
                isRefreshing = false;
            }
            error.err && ElMessage.error(error.err);
        } finally {
        }

    } else if (res.status === 403) {
        ElMessage.error('权限不足！请联系管理员！');
    } else {
        isRefreshing = false;
        ElMessage.error(res.data?.msg||'Error:请求失败！'+res.status);
    }
    return Promise.reject(error);
});

export default service